<?php
namespace App\Models\ActivityInfo;

use App\Contracts\Repositories\ActivityInfoRepository as ActivityRepositoryContract;
use App\Models\ActivityRecord\ActivityRecord;
use App\Models\Prize\Prize;

class ActivityInfoRepository implements ActivityRepositoryContract
{
    /**
     * @param array $activity
     * @return mixed
     */
    public function create($activity)
    {
        $activity['created_at'] = date('Y-m-d H:i:s');
        $activity['updated_at'] = date('Y-m-d H:i:s');
        $activityId = ActivityInfo::insertGetId($activity);
        return $activityId;
    }

    /**
     * @param array $activity
     * @param array $conditions
     * @return mixed
     */
    public function modify($activity, $conditions)
    {
        return ActivityInfo::where($conditions)->update($activity);
    }

    /**
     * @param array $conditions
     * @param bool $softDeletion
     * @return mixed
     */
    public function delete($conditions, $softDeletion)
    {
        if ($softDeletion == true) {
            return ActivityInfo::where($conditions)->update(array('deleted_at' => date('Y-m-d H:i:s')));
        } else {
            return ActivityInfo::with('ActivityRecord')->where($conditions)->delete();
        }
    }

    /**
     * @param int $activityId
     * @return mixed
     */
    public function findById($activityId)
    {
        if (is_array($activityId)) {
            return ActivityInfo::with('prize', 'activityRecord', 'prizeRecord')->whereIn('id', $activityId)->get()->toArray();
        } else {
            return ActivityInfo::with('prize', 'activityRecord', 'prizeRecord')->find($activityId)->toArray();
        }
    }

    /**
     * @param array $conditions
     * @param array $withs
     * @return null
     */
    public function findByConditions($conditions, $withs)
    {
        if (is_array($withs) || is_string($withs) || is_null($withs)) {
            return ActivityInfo::with($withs)->where($conditions)->get();
        } else {
            return null;
        }
    }

    /**
     * @param int $activityId
     * @param array $activityRecords
     * @return mixed
     */
    public function updateActivityRecords($activityId, $activityRecords)
    {
        return ActivityInfo::find($activityId)->activityRecord()->save(new ActivityRecord($activityRecords));
    }

    /**
     * @param $activityId
     * @param $prizeId
     * @return mixed
     */
    public function updateActivityPrize($activityId, $prizeId)
    {
        return ActivityInfo::find($activityId)->prize()->attach($prizeId);
    }

    /**
     * @param int $prizeId
     * @return mixed
     */
    public function getPrizeInfo($prizeId)
    {
        return Prize::with('prizeType', 'sponsor')->find($prizeId)->toArray();
    }
}
